package com.dtflys.forest.testserver.controller;

import com.dtflys.forest.testserver.client.UploadClient;
import com.dtflys.forest.testserver.service.FileService;
import com.dtflys.forest.testserver.utils.PathUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Map;

@RestController
public class TestUploadController {

    private final static Logger logger = LoggerFactory.getLogger(TestUploadController.class);

    @Autowired
    private FileService fileService;

    @Value("${myfile.uploadPath}")
    private String uploadPath;

    @javax.annotation.Resource
    private UploadClient uploadClient;


    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    //处理文件上传的方法
    @PostMapping("/upload")
    public Map upload(MultipartFile file, HttpServletRequest request, @RequestParam("flag") String flag) throws IOException {
        String webPath = "upload";
        System.out.println("webPath=" + webPath);
        String webFilePath = PathUtil.appendWebPath(webPath, file.getOriginalFilename());
        System.out.println("webFilePath=" + webFilePath);
        String filePath = PathUtil.appendWebPath(uploadPath, webFilePath);
        System.out.println("filePath=" + filePath);
        Map<String, String> result = fileService.uploadReal(filePath, file);
        result.put("webUrl", webFilePath);
        return result;
    }

    //处理文件上传的方法
    @PostMapping("/upload2")
    public Map upload2(MultipartFile file, @RequestParam("username") String username, HttpServletRequest request) throws IOException {
        String webPath = "upload";
        System.out.println("username=" + username);
        System.out.println("webPath=" + webPath);
        String webFilePath = PathUtil.appendWebPath(webPath, file.getOriginalFilename());
        System.out.println("webFilePath=" + webFilePath);
        String filePath = PathUtil.appendWebPath(uploadPath, webFilePath);
        System.out.println("filePath=" + filePath);
        Map<String, String> result = fileService.uploadReal(filePath, file);
        result.put("webUrl", webFilePath);
        return result;
    }



    @PostMapping("/do-upload-file-path")
    public Map doUploadFilePath() {
        Map result = uploadClient.upload("D:\\TestUpload\\source\\test-img.jpg", "xxx", progress -> {
            logger.info("-------------------------------------------------------");
            logger.info("total bytes: " + progress.getTotalBytes());
            logger.info("current bytes: " + progress.getCurrentBytes());
            logger.info("uploaded: " + (progress.getRate() * 100) + "%");
        });
        return result;
    }

    @PostMapping("/do-upload-file-path-test2")
    public Map doUploadFilePathTest2() {
        Map result = uploadClient.uploadTest2("D:\\TestUpload\\source\\test-img.jpg", progress -> {
            logger.info("-------------------------------------------------------");
            logger.info("total bytes: " + progress.getTotalBytes());
            logger.info("current bytes: " + progress.getCurrentBytes());
            logger.info("uploaded: " + (progress.getRate() * 100) + "%");
        });
        return result;
    }


    @PostMapping("/do-upload-file")
    public Map doUploadFile() {
//        File file = new File("D:\\TestUpload\\source\\test-img.jpg");
        File file = new File("D:\\TestUpload\\source\\test-img.jpg");
        Map result = uploadClient.upload(file, "1", progress -> {
            logger.info("-------------------------------------------------------");
            logger.info("total bytes: " + progress.getTotalBytes());
            logger.info("current bytes: " + progress.getCurrentBytes());
            logger.info("uploaded: " + (progress.getRate() * 100) + "%");
        });
        return result;
    }

    @PostMapping("/do-upload-bytes")
    public Map doUploadBytes() {
        File file = new File("D:\\TestUpload\\source\\test-img.jpg");
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map result = uploadClient.upload(buffer, "test-bytes.jpg", "xxx");
        return result;
    }


    @PostMapping("/do-upload-input-stream")
    public Map doUploadInputStream() {
        File file = new File("D:\\TestUpload\\source\\test-img.jpg");
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Map result = uploadClient.upload(fis, "test-input-stream.jpg", "xxx");
        return result;
    }

    @PostMapping("/do-upload-resource")
    public Map doUploadResource() {
        Resource resource = new ClassPathResource("test-img.jpg");
        Map result = uploadClient.upload(resource, "xxx");
        return result;
    }

    @PostMapping("/do-upload-multipart-file")
    public Map doUploadMultipartFile(MultipartFile multipartFile)  {
        Map result = uploadClient.upload(multipartFile, "xxx", progress -> {
            logger.info("-------------------------------------------------------");
            logger.info("total bytes: " + progress.getTotalBytes());
            logger.info("current bytes: " + progress.getCurrentBytes());
            logger.info("uploaded: " + (progress.getRate() * 100) + "%");
            logger.info("is done: " + progress.isDone());
        });
        return result;
    }

    @PostMapping("/do-upload-multipart-file-test2")
    public String doUploadMultipartFileTest2(MultipartFile multipartFile)  {
        String result = uploadClient.uploadTest2(multipartFile);
        return result;
    }


    @PostMapping("/do-upload-multipart-file2")
    public Map doUploadMultipartFile2(MultipartFile multipartFile)  {
        Map result = uploadClient.upload3("test", "11", "uuid", multipartFile);
        return result;
    }



}
